home *** CD-ROM | disk | FTP | other *** search
- #
- # This file is part of OpenVIP (http://openvip.sourceforge.net)
- #
- # Copyright (C) 2002-2003
- # Michal Dvorak, Jiri Sedlar, Antonin Slavik, Vaclav Slavik, Jozef Smizansky
- #
- # This program is licensed under GNU General Public License version 2;
- # see file COPYING in the top level directory for details.
- #
- # $Id: notify.py,v 1.4 2003/06/03 21:01:13 vaclavslavik Exp $
- #
- # Notifications mechanism
- #
-
- import weakref
-
- # Notification events:
- CHANGED = 'changed'
- DELETED = 'deleted'
-
-
- # Map of notification callbacks:
- class NotificationEntry:
- def __init__(self):
- self.callbacks = {}
- __listener = {}
-
- def __doNotify(entry, event):
- if event in entry.callbacks:
- for cb in entry.callbacks[event]:
- cb()
-
- def __onDelete(weak):
- __doNotify(__listener[weak], DELETED)
- del __listener[weak]
-
- def __getEntry(object):
- idx = weakref.ref(object)
- if idx not in __listener:
- idx = weakref.ref(object, __onDelete)
- __listener[idx] = NotificationEntry()
- return __listener[idx]
-
-
- # -------------------------------------------------------------
- # Public functions:
- # -------------------------------------------------------------
-
- def listen(object, callback, event = CHANGED):
- """Adds callback to the list of functions to call when given event
- happens to object. The callback is called only when somebody
- calls notify(object,event), not automatically!"""
- c = __getEntry(object).callbacks
- if event not in c:
- c[event] = [callback]
- else:
- c[event].append(callback)
-
- def unlisten(object, callback, event = CHANGED):
- """Removes callback registered using listen()."""
- __getEntry(object).callbacks[event].remove(callback)
-
- def notify(object, event = CHANGED):
- """Sends notification to all listeners registered with object."""
- __doNotify(__getEntry(object), event)
-